<?php
/**
 * Created by PhpStorm.
 * User: 牛赞赞
 * Date: 2020/12/31
 * Time: 14:20
 */

namespace App\Game\Logic;

use App\Game\Conf\GameProgress;
use App\Game\Conf\MainCmd;
use App\Game\Conf\SubCmd;
use App\Game\Core\AStrategy;
use App\Game\Core\Message;
use App\Game\Core\Packet;
use App\Game\Core\Room;
use App\Task\RobotAssignTask;

class RoomQuit extends AStrategy
{
    /**
     * 退出未开始游戏的房间
     */
    public function exec()
    {
        $account = $this->_params['userinfo']['account'];
        $game_conf = $this->game_conf;
        $user_room_map_key = sprintf($game_conf['user_room'], $account);
        $room_no = redis()->get($user_room_map_key);
        $chair_id = $this->_params['data']['chair_id'];
        $fd = $this->_params['userinfo']['fd'];
//        $room_data = getRoomData($room_no);
//        $msg = ['status' => '退出成功', 'chair_id' => $chair_id];

//        if (empty($room_data)) {
//            ddTitle('t-1');
//            $serv = server();
//            $fd = $this->_params['userinfo']['fd'];
//            pushDataToUser($serv, $fd, $msg, SubCmd::FORCE_QUIT_ROOM_RESP);
//            $this->roomBroadcast($room_no, $chair_id);
//            return;
//        }
        ddTitle('q1');
        $game_type = intval(Room::getRoomData($room_no, 'game_type'));
        dd('game_type', $game_type);
        if ($game_type != 0) { //非普通局
            ddTitle('q2');
            return;
        }

        if (checkGameProgress($room_no, [GameProgress::GAME_OUT_CARD, GameProgress::GAME_CHECK_HPG,
            GameProgress::GAME_CHANGE_CARD, GameProgress::GAME_CHOOSE_COLOR])) {
            ddTitle('q3');
            setTakeOverByAccount($room_no, $account);
            $msg = ['status' => '退出成功', 'chair_id' => $chair_id];
            Message::pushDataToUser($account, $msg, SubCmd::SUB_GAME_ROOM_QUIT_RESP);
            return;
        }
        ddTitle('q4');
        $this->roomBroadcast($room_no, $chair_id, $fd);

        //从房间绑定集合中剔除该玩家
        removeRoomMapByAccount($account);
        //从等待集合中剔除该玩家
        removeRoomWaitByAccount($room_no, $account);
        removeRoomChairByAccount($room_no, $account);
        //更新房间该玩家的状态为退出
//        playerQuit($room_no, $account);
        removeGamePrepareByAccount($room_no, $account);

        $ptype = getGameProgressType($room_no);
        if ($ptype) { //单机
            clearRoomDataAll($room_no);
            return;
        }

        $waiters = getRoomWait($room_no);
//        dd('waiters', $waiters);
        //如果没有准备玩家则清除房间所有数据
        if (!count($waiters)) {
            //清除游戏数据
            clearRoomDataAll($room_no);
            ddTitle('房间清除成功1');
            return;
        }
        if (!isGameOver($room_no)) {
            //更新房间该玩家的状态为托管
            setTakeOverByAccount($room_no, $account);
        } else {
            removeRoomWaitByAccount($room_no, $account);
        }
        $waiters = getRoomWait($room_no);
        //如果没有准备玩家则清除房间所有数据
        if (!count($waiters)) {
            //清除游戏数据
            clearRoomDataAll($room_no);
            ddTitle('房间清除成功2');
            return;
        }
//        $flag = false; //剩余玩家状态
//        foreach ($waiters as $cid => $acc) {
//            $ps = playerStatus($room_no, $acc);
//            if (in_array($ps, [GameProgress::USER_OFFLINE, 0])) { //如果掉线或者托管，则设置标志为true
//                $flag = true;
//            } else {
//                $flag = false;
//            }
//        }
//        if ($flag) { //如果剩余的玩家全部都是掉线或者托管状态则直接清除房间信息
//            //清除游戏数据
//            clearRoomDataAll($room_no);
//            ddTitle('房间清除成功3');
//            return;
//        }
    }

    /**
     * 返回不包含自身数组
     * @param $cache
     * @param $origin
     * @return mixed
     */
    public function kickOut($cache, $origin)
    {
        $robot_conf = config('robot');
        $robot_arr = $robot_conf['robots'];
        $cacheArr = json_decode($cache, true);
        if (!empty($cacheArr)) {
            if (in_array($origin, $cacheArr)) {
                $cacheArr = array_diff($cacheArr, [$origin]);
            }
        }
        $new_users = [];
        $robot_user = [];
        foreach ($cacheArr as $v) {
            if (!in_array($v, $robot_arr)) {
                $new_users[] = $v;
            } else {
                $robot_user[] = $v;
            }
        }
        return ['left_user' => $new_users, 'robot_user' => $robot_user];
    }


    /**
     * 房间广播
     * @param $serv
     * @param $chair_id
     * @param $fds
     */
    protected function roomBroadcast($room_no, $chair_id, $user_fd = false)
    {
        ddTitle('t-2');
        $serv = server();
        $msg = ['status' => '退出成功', 'chair_id' => $chair_id];
        $data = Packet::packFormat('OK', 1, $msg);
        $room_data = Packet::packEncode($data, MainCmd::CMD_SYS, SubCmd::SUB_GAME_ROOM_QUIT_RESP);
        if ($user_fd) {
            $serv->push($user_fd, $room_data, WEBSOCKET_OPCODE_BINARY);
        }
        $fds = getOtherFdsByRoomNo($room_no);
        foreach ($fds as $fd) {
            if ($fd != $user_fd) {
                //获取客户端信息
//                $client_info = $serv->getClientInfo($fd);
//                $client[$fd] = $client_info;
//                if (isset($client_info['websocket_status']) && $client_info['websocket_status'] == 3) {
                $serv->push($fd, $room_data, WEBSOCKET_OPCODE_BINARY);
//                }
            }
        }
    }

    /**
     * 清除机器人map
     * @param $robot_arr
     */
    protected function cleanRobotMap($robot_arr)
    {
        $game_conf = config('game');
        foreach ($robot_arr as $k => $v) {
            $user_map_key = sprintf($game_conf['user_room'], $v);
            redis()->del($user_map_key);
        }
    }
}